// 主界面
;
define(function(require, exports, module) {
	'use strict';
	var util = require("util");
	var base = require("base");
	var dialog = require("dialog");
	var validate = require("validate");
	var css_param = require("./createPickupDetail.css");
	var css_common = require("../../../css/common.css");
	var tools = require("tools");
	var router = require("../hash/pageRouter");
	var leftMenu = require("../leftMenu/leftMenu");
	var databind = require("databind");
	var constant = require("constant");
	var pickupId;
	var pageIndex = 1,
        pageSize = 10,
        totalPageCount = 1,
        totalRecordCount = 0; //分页初始化
    var html_bulkstockInfo = require("./html_bulkstockInfo.html");//查询货物弹出框内容
	var init = function(page) {
		pickupId = page.params.pickupId || base.getUrlParam("pickupId");
		initPickUpDetail(pickupId);
//		leftMenu.init(11);
		initEvent();
	};
	var initEvent = function() {
		//查看审批记录
		$("#createPickupDetail .auditRecord").unbind("click").click(function(){
			window.open("../auditRecord/auditRecord.html?recordType=7&recordId=" + pickupId);
		});
		
		//查看融资详情
		$("#createPickupDetail tr[class='trFinanceDetail']").hide();
		$("#createPickupDetail").on("click", ".showFinanceDetail", function() {
			var $thisParent = $(this).parents("tr");
			var financeId = $thisParent.attr("financeId");
			if($thisParent.next().is(":hidden")) {
				$thisParent.next().show();
				$(this).html("&nbsp;&nbsp;[-]");
			}else {
				$thisParent.next().hide();
				$(this).html("&nbsp;&nbsp;[+]");
			}
			
			if($thisParent.next().attr("isNull") != "1") {
				inquireFinanceApplicationDetail($thisParent.next(),financeId);
			}
		});
		
		//点击融资编号
		$("#createPickupDetail .order_num").unbind("click").click(function() {
			router.route("financing/financingDetailInfo.html?financeId=" + $(this).parents("tr").attr("financeId"));
		});
	};
	
	//提货详情
	var initPickUpDetail = function(pickupId) {
		base.fnAjax({
			action: "inquireFinancePickupApplicationWarehouse.json",
			async: false,
			oData: {
				pickupId: pickupId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					if(data.datas.length > 0) {
						juicer.register("formatCurrency", tools.formatCurrency);
						juicer.register("getValueByKey", constant.getValueByKey);
						
						databind.fillForm($("#createPickupDetail"), data.datas[0]);
						
						var pickUpInfoTmpl = $("#createPickupDetail #pickUpInfoTmpl").html();
						var html = juicer(pickUpInfoTmpl, data);
						$("#createPickupDetail .content1").html(html);
						
						if(data.datas[0].filesUuid != undefined) {
							var filesUuid = data.datas[0].filesUuid;
							var tableBody = "";
							var index = 1;
							$.each(filesUuid.split(","), function() {
								var _this = this;
								if($.trim(_this) != "") {
									tableBody += '<tr><td>'+index+'</td><td>'+ tools.inquireFile(_this) +'</td><td><a target="_blank" class="table_details_link" fileUuid="' + _this + '" href="/finance/api/v1.0/downloadFile.file?fileUuid=' + _this + '" >' + "预览" + '</a></td></tr>';
								}
								index = index + 1;
							});
							
							$("#createPickupDetail .fileUuidBody").html(tableBody);
							databind.disableInput("#createPickupDetail");
						}
						
						$("#createPickupDetail .pickupForm table").html("<tr><th><input type='checkbox' class='checkAll none'></th><th>No</th><th>文件名称</th><th>文件类型</th><th>状态</th><th class='none'>签署记录</th><th class='none'>退回原因</th><th>操作</th></tr>")
						var i = 1;
						$.each(data.datas[0].financeFilesInfoList, function() {
							var isSign = this.isSign;
							var filesInfoId = this.filesInfoId;
							var signState = this.fileSignState.split(',');
							var msg = [];
							if (this.msg != null) {
								msg = this.msg.split(',');
							}
							var j = 0;
							var fs1 = this.filesUuid.split(',');
							var ss1 = this.isSign.split(',');
	//						$.each(this.filesUuid.split(','), function() {
							for (var x = 0; x < fs1.length; x++) {
								var _this = fs1[x];
								if ($.trim(_this) != "") {
									var m = msg[j];
									if (m == null || m == "null") {
										m = "";
									}
									var str;
									if (ss1[x] == '1') {
										str = "<tr signState='"+signState[j]+"' fileUuid='"+_this+"' filesInfoId='"+filesInfoId+"' ><td><input checked='checked' type='checkbox' class='checks none'></td><td>"+i+"</td><td>"+tools.inquireFile(_this)+"</td><td>签署文件</td><td>"+constant.getValueByKey(73, signState[j])+"</td><td class='none'><a href='javascript:void(0);' class='showSignRecord'>查看</td><td class='none'>"+m+"</td><td><a target='_blank' href='/finance/api/v1.0/viewPdfFile.json?fileUuid="+_this+"'>预览</a></td></tr>";
									} else {
										str = "<tr signState='"+signState[j]+"' fileUuid='"+_this+"' filesInfoId='"+filesInfoId+"' ><td><input type='checkbox' disabled='disabled' class='none'></td><td>"+i+"</td><td>"+tools.inquireFile(_this)+"</td><td>附件</td><td>-</td><td class='none'></td><td><a target='_blank' href='/finance/api/v1.0/viewPdfFile.json?fileUuid="+_this+"'>预览</a></td></tr>";
									}
									if (str != null) {
										$("#createPickupDetail .pickupForm table").append(str);
										i++;
										str = null;
									}
									m = "";
									j++;
								}
							};
							
							tools.addCheckAllEvent($(".html_documentSign .checks"), $(".html_documentSign .checkAll"));
						});
						
						//提货信息合计
						var supervisionQuantitys = 0;
						$.each($("#createPickupDetail .supervisionQuantity"), function() {
							supervisionQuantitys += parseFloat($(this).attr("supervisionQuantity"));
						});
						$("#createPickupDetail #supervisionQuantitys").html(tools.formatCurrency(supervisionQuantitys.toFixed(2)));
						
						var pickupQuantitys = 0;
						$.each($("#createPickupDetail .pickupQuantity"), function() {
							pickupQuantitys += parseFloat($(this).attr("pickupQuantity"));
						});
						$("#createPickupDetail #pickupQuantitys").html(tools.formatCurrency(pickupQuantitys.toFixed(2)));
						
						var bulkstockAmount = 0;
						$.each($("#createPickupDetail .bulkstockAmount"), function() {
							bulkstockAmount += parseFloat($(this).attr("bulkstockAmount"));
						});
						$("#createPickupDetail #bulkstockAmount").html(tools.formatCurrency(bulkstockAmount.toFixed(2)));
						
						var interest = 0;
						$.each($("#createPickupDetail .interest"), function() {
							interest += parseFloat($(this).attr("interest"));
						});
						$("#createPickupDetail #interest").html(tools.formatCurrency(interest.toFixed(2)));
						
						var others = 0;
						$.each($("#createPickupDetail .others"), function() {
							others += parseFloat($(this).attr("others"));
						});
						$("#createPickupDetail #others").html(tools.formatCurrency(others.toFixed(2)));
						
						var pickupAmounts = 0;
						$.each($("#createPickupDetail .pickupAmount"), function() {
							pickupAmounts += parseFloat($(this).attr("pickupAmount"));
						});
						$("#createPickupDetail #pickupAmounts").html(tools.formatCurrency(pickupAmounts.toFixed(2)));
						
					}
					
					var step = 1;
					if (data.datas[0].finalId == 25) {
						step = 1;
					} else if (data.datas[0].finalId == 5) {
						step = 2;
					} else if (data.datas[0].finalId == 3) {
						step = 3;
					} else if (data.datas[0].finalId == 9) {
						step = 4;
					} else if (data.datas[0].finalId == 10) {
						step = 5;
					} else if (data.datas[0].finalId == 20) {
						step = 6;
					} else if (data.datas[0].finalId == 14) {
						step = 7;
					}
					
					$.each($("#createPickupDetail table tr"), function() {
						
						var _this = $(this)
						if (_this.attr("financeNumber") != null && _this.attr("financeNumber") != "") {
							inquireFinanceApplicationDetailByFinanceNUmber(_this.attr("financeNumber"), function(data){
						  		//回调
						  		_this.find(".financeNumber").append(data.datas[0].financeNumber + '<input type="hidden" name="financeNumbers" value="'+data.datas[0].financeNumber+'" /><input type="hidden" name="financeIds" value="'+data.datas[0].financeId+'" />');
						  		_this.find(".productType").html(constant.getValueByKey(7, data.datas[0].productType));
						  		_this.find(".financeBulkstock").html(data.datas[0].bulkstocks[0].bulkstockName + "(" + data.datas[0].bulkstocks[0].specification + ")");
						  		_this.find(".waitReceipt").html(tools.formatCurrency(data.datas[0].totalLoanAmount - data.datas[0].totalReceivedAmount));
							});
						}
			
					});
					
					tools.stepBar($("#createPickupDetailStepBar"), step, [{name: "商务部审核", id: 1}, {name: "运营审核", id: 2}, {name: "风控审核", id: 3}, {name: "资金审核", id: 4}, {name: "资金领导审核", id: 5}, {name: "副总经理审核", id: 6}, {name: "审核完成", id: 7}]);
				}else {
					base.alert(2, "获取信息失败");
					return;
				}
			}
		});
	};
	
	//查询融资详情
	var inquireFinanceApplicationDetail = function(dom,financeId) {
		base.fnAjax({
			action: "inquireFinanceApplicationDetail.json",
			nocode: true,
			oData: {
				financeId: financeId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					var d = {};
					d.loanDate = data.datas[0].loanDate;
					d.loanAmount = tools.formatCurrency(data.datas[0].loanAmount);
					d.intrerst = data.datas[0].auditInterest;
					d.pledgeRate = (parseFloat(data.datas[0].financeAuditDetail.financeAmount)*100/parseFloat(data.datas[0].bulkstocks[0].finalPrice)).toFixed(2);
					d.financeDays = data.datas[0].financeProductInnerDetail.financeDays;
					d.bulkstockPrice = tools.formatCurrency(data.datas[0].bulkstocks[0].bulkstockPrice);
					d.financePrice = tools.formatCurrency(data.datas[0].bulkstocks[0].financePrice);
					
					databind.fillForm(dom, d);
					
					dom.attr("isNull", "1");
				}else {
					//
				}
			}
		})
	};
	
	//查询融资详情
	var inquireFinanceApplicationDetailByFinanceNUmber = function(financeNumber, callback) {
//		if (financeNumber == null || financeNumber == "") {
//			base.alert(3, "请输入融资编号！");
//			return false;
//		}
		
		base.fnAjax({
			action: "inquireFinanceApplicationDetailByFinanceNUmber.json",
			nocode: true,
			oData: {
				financeNumber: financeNumber
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
//					var d = {};
//					d.loanDate = data.datas[0].loanApplicationCreateDatetime;
//					d.loanAmount = tools.formatCurrency(data.datas[0].financeAmount);
//					d.interestRate = data.datas[0].auditInterest + "%";
//					d.financeDays = data.datas[0].financeProductInnerDetail.financeDays;
//					d.financeNumbers = data.datas[0].financeNumber;
//					d.financeIds = data.datas[0].financeId;
//					d.productType = constant.getValueByKey(7, data.datas[0].productType);
//					d.bulkstockName= data.datas[0].bulkstocks[0].bulkstockName + "("　+ data.datas[0].bulkstocks[0].specification +　")";
//					d.financeContractSerialNumber = data.datas[0].financeContractDetail.financeContractSerialNumber;
//					d.waitReceipt = data.datas[0].financeAmount-data.datas[0].totalReceivedAmount;
//					d.deadLine = tools.addDate(data.datas[0].loanApplicationCreateDatetime, data.datas[0].financeProductInnerDetail.financeDays);
//					
//					databind.fillForm(dom, d);
					callback(data);
				}else {
					base.alert(3, data.message);
				}
			}
		})
	};
	
	return {
		init: init
	};
});